package com.apkfuns.jsbridge.view.slice;

import com.apkfuns.jsbridge.JsBridge;
import com.apkfuns.jsbridge.LogUtils;
import com.apkfuns.jsbridge.ResourceTable;
import com.apkfuns.jsbridge.common.IPromptResult;
import com.apkfuns.jsbridge.common.IWebView;
import com.apkfuns.jsbridge.module.ListenerModule;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.webengine.*;
import ohos.agp.utils.TextTool;
import ohos.app.Context;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.net.URLConnection;

public class CustomWebViewAbilitySlice extends AbilitySlice {
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00203, "CustomWebViewAbilitySlice");
    private JsBridge jsBridge;
    private CustomWebView customWebView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
       // super.setUIContent(ResourceTable.Layout_ability_custom_web_view);
        jsBridge = JsBridge.loadModule();
        customWebView = new CustomWebView(this);
        //setContentView(customWebView);
         DirectionalLayout myLayout =  new DirectionalLayout(this);
        DirectionalLayout.LayoutConfig config = new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_PARENT, DirectionalLayout.LayoutConfig.MATCH_PARENT);
        myLayout.setLayoutConfig(config);


        customWebView.setLayoutConfig(config);

        myLayout.addComponent(customWebView);
        super.setUIContent(myLayout);


        class JsWebAgent extends  WebAgent {
            @Override
            public void onPageLoaded(WebView webView, String url) {
                super.onPageLoaded(webView, url);
                jsBridge.injectJs(getAbility(),webView);
            }

            @Override
            public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
                final String authority = "example.com";
                final String rawFile = "/rawfile/";
                Uri requestUri = request.getRequestUrl();
                if (authority.equals(requestUri.getDecodedAuthority())) {
                    String path = requestUri.getDecodedPath();
                    if (TextTool.isNullOrEmpty(path)) {
                        return super.processResourceRequest(webView, request);
                    }
                    if (path.startsWith(rawFile)) {
                        // 根据自定义规则访问资源文件
                        String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
                        String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                        try {
                            Resource resource = getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                            return new ResourceResponse(mimeType, resource, null);
                        } catch (IOException e) {
                            HiLog.info(LABEL, "open raw file failed");
                        }
                    }
                }
                return super.processResourceRequest(webView, request);
            }
        }

        customWebView.setWebViewClient(new JsWebAgent());
        customWebView.setPromptResult(new PromptResultCallback() {

            @Override
            public void onResult(String args, PromptResultImpl promptResult) {
                jsBridge.callJsPrompt(args, promptResult);
            }

        });
        customWebView.loadUrl(getString(ResourceTable.String_coustom_webview_url));
    }

    @Override
    public void onActive() {
        super.onActive();
        ListenerModule.onResume(customWebView, "hello");
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        ListenerModule.onPause(customWebView, 2);
    }


    @Override
    public void terminateAbility() {
        jsBridge.release();
        super.terminateAbility();

    }


    public static class CustomWebView extends DirectionalLayout implements IWebView {

        private WebView cWebView;
        private PromptResultCallback promptResultCallback;

        public CustomWebView(Context context) {
            super(context);
            cWebView = new WebView(context);
            cWebView.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
            cWebView.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
            cWebView.getWebConfig() .setJavaScriptPermit(true);  // 如果网页需要使用JavaScript，增加此行；如何使用JavaScript下文有详细介绍
            addComponent(cWebView);
            //addView(this.webView);
            cWebView.setBrowserAgent(new BrowserAgent(getContext()) {

                @Override
                public boolean onJsMessageShow(WebView webView, String url, String message, boolean isAlert, JsMessageResult result) {
                    LogUtils.info("CustomWebViewAbilitySlice","JACK onJsMessageShow3 " + message);
                    return super.onJsMessageShow(webView, url,message,isAlert,result);
                }

                @Override
                public boolean onJsTextInput(WebView webView, String url, String message, String defaultInput, JsTextInputResult result) {
                    LogUtils.info("CustomWebViewAbilitySlice","JACK onJsTextInput3 " + message);
                    if (promptResultCallback != null) {
                        promptResultCallback.onResult(message, new PromptResultImpl(result));
                    }
                    return true;
                    //return super.onJsTextInput(webView, url, message, defaultInput, result);
                }
            });

        }

        public void setWebViewClient(WebAgent webViewClient) {
            this.cWebView.setWebAgent(webViewClient);
        }

        @Override
        public void loadUrl(String url) {
            cWebView.load(url);
        }

      //  @Override
       // public Context getContext() {
       //     return null;
       // }

        public void setPromptResult(final PromptResultCallback callback) {
            this.promptResultCallback = callback;
        }
    }


    public static class PromptResultImpl implements IPromptResult {
        private JsTextInputResult jsPromptResult;

        public PromptResultImpl(JsTextInputResult j) {
            this.jsPromptResult = j;
        }

        @Override
        public void confirm(String result) {

            this.jsPromptResult.respond(result);
        }
    }

    public interface PromptResultCallback {
        void onResult(String args, PromptResultImpl promptResult);
    }
}
